/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.isystem.autpart.dao;

import java.io.Serializable;
import java.util.List;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.isystem.autpart.util.HibernateUtil;

/**
 *
 * @author Miguel
 */
public class DAOGeneral {
    private SessionFactory sessFact;
    private Session sess;
    private Transaction tr;

    public DAOGeneral() {

        this.sessFact = HibernateUtil.getSessionFactory();
        this.sess = sessFact.openSession();
        this.tr = sess.beginTransaction();

    }

    public void evict(Object obj) {
        sess.evict(obj);
//        sess.flush();
    }

    public void refresh() {
//        this.Close();
        this.Open();
    }

    public void Open() {

        this.sessFact = HibernateUtil.getSessionFactory();
        this.sess = sessFact.openSession();
        this.tr = sess.beginTransaction();
    }

    public void Close() {
        sess.clear();
//        sess.close();
//        sessFact.close();
    }

//    public abstract Object load(Object id);
    public Object load(Class x, Object id) {
        if (sess.get(x, (Serializable) id) == null) {
            return null;
        }
        Object p = sess.load(x, (Serializable) id);
        return p;
    }

    public void persist(Object obj) {
        tr = sess.beginTransaction();
        sess.persist(obj);
        tr.commit();
//        sess.close();
//        sessFact.close();
    }

    public List findAll(String Hql) {
        Query query = sess.createQuery(Hql);
        List result = query.list();
        return result;
    }

    public Object findOne(String Hql) {
        Query query = sess.createQuery(Hql);
        Object result = query.list().get(0);
        return result;
    }

    public void delete(Object obj) {
        tr = sess.beginTransaction();
        sess.delete(obj);
        tr.commit();
        //sess.close();
        // sessFact.close();
    }

    public void update() {
        tr = sess.beginTransaction();
        tr.commit();
    }
//    public void update(Object object) {
//        tr = sess.beginTransaction();
//        sess.update(object);
//        tr.commit();
//    }
    
    public String md5(String cadena){
        try{
            Query q = sess.createSQLQuery("Select md5('" + cadena + "')");
            return (String) q.list().get(0);
        }catch (Exception e){
            System.out.println("error "  + e.getMessage());
            return "";
        }
    }
}
